package com.cloud.mqtt.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * @Author: JohnCoding
 * @Description: Deflater工具类 解压工具类
 * @date: 2020/6/18 14:04
 */
public class DefalterUtil {


    /**
     * 解压byte数组
     * @param data
     * @return
     * @throws Exception
     */
    public static String unCompress(byte[] data) throws Exception {
        Inflater inflater = new Inflater(true);
        inflater.setInput(data);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        try {
            //创建字节数组读取
            byte[] buff = new byte[1024];
            while (!inflater.finished()) {
                int count = inflater.inflate(buff);
                //用输出流写出
                outputStream.write(buff, 0, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            outputStream.close();
        }
        inflater.end();
        //转码
        return new String(outputStream.toByteArray(), "GBK");
    }

    public static byte[] compress(byte[] data) throws IOException {
        byte[] output;
        Deflater compress = new Deflater();

        compress.reset();
        compress.setInput(data);
        compress.finish();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
        try {
            byte[] buf = new byte[1024];
            while (!compress.finished()) {
                int i = compress.deflate(buf);
                bos.write(buf, 0, i);
            }
            output = bos.toByteArray();
        } catch (Exception e) {
            output = data;
            e.printStackTrace();
        } finally {
            bos.close();
        }
        compress.end();
        return output;
    }


}
